const user = require("./config/user");
const aiFun = require("./src/ai");
const getData = require("./src/getData");
const saveAsin = require("./src/saveAsin");
const webdriver = require("selenium-webdriver");
const chalk = require("chalk");
const By = webdriver.By;
const until = webdriver.until;
const driver = new webdriver.Builder().forBrowser("chrome").build();
//不启动浏览器模式，速度更快  这里引入要输入 验证码，不能用
// const chromeDriver = require("selenium-webdriver/chrome");
// const driver = new webdriver.Builder()
//   .forBrowser("chrome")
//   .setChromeOptions(new chromeDriver.Options().addArguments(["headless"]))
//   .build();
let q  = 3583;
let asinArr = [];
let asinArrLength = 0;
let asin = "";
async function start() {
  //准备 asin数据
  await getData().then((data) => {
    asinArr = data;
  });
  console.log("input", user.country, "    ", "./data/" + user.input + ".txt");
  console.log("output", user.output + ".txt");
  asinArrLength = asinArr.length;
  console.log(asinArrLength);
  signin();
}
// 登录
async function signin (){
  await driver.get("https://sellercentral.amazon.com/home");
  await driver.findElement(By.id("ap_email")).sendKeys(user.name);
  await driver.sleep(1 * 1000);
  await driver.findElement(By.id("ap_password")).sendKeys(user.password);
  await driver.sleep(1 * 1000);
  //在10s内id是foo的元素被定位到，然后点击之
  let button = driver.wait(until.elementLocated(By.id("signInSubmit")), 300);
  await button.click();
  // 输入 登录 code 验证
  aiFun(nextFun);

}
// aiFun 的回调函数
async function nextFun(code) {
  //正式 登录
  await driver.findElement(By.id("auth-mfa-otpcode")).sendKeys(code);
  let button = driver.wait(until.elementLocated(By.id("auth-signin-button")), 10);
  await button.click();
  await driver.sleep(30 * 1000);
  // await selectCountry();
  await driver.get("https://sellercentral.amazon.com/productsearch/ref=xx_catadd_dnav_xx");
  // 寻找 asin
  searchAsin();
}
// async function selectCountry(){
//   console.log("选择国家");
//   await driver.findElements(By.xpath("//*[@id='sc-mkt-picker-switcher-select']/optgroup[1]/option")).then(function (options) {
//     // 这个地方需要根据账号来判断，因为每个账号开通的国家不一样，你想要的点击的就不同
//     options[options.length - 2].click();
//   });
// }

// searchAsin 寻找满足需求的asin;
async function searchAsin() {
  asin = asinArr[q];
  console.log("展开==start==========  " + q + "  ====  " + asin + "  ===========");
  if (asin === undefined && q > asinArrLength) {
    console.log("没有了");
    driver.quit(); //关闭浏览器
  }
  //输入 需要查询的asin  点击查询 ===============
  try{
    let inputSearch = driver.findElement(By.id("product-search"));
    await inputSearch.clear();
    await inputSearch.sendKeys(asin);
    let searchButton = driver.wait(until.elementLocated(By.xpath("//*[@id='product-search-button']/span/input")), 100);
    await searchButton.click();
  }catch(err){
    console.log(chalk.red("输入阶段有错误，执行下一个"));
    // reExecution();
  }
  //检查是否有弹框 // ====展开===============B00FAU3BLK
  closeFrame("button ", showButton);
}
//关闭弹窗
async function closeFrame(msg, callback) {
  await driver.sleep(3 * 1000);
  await driver.findElement(By.xpath("//*[@id='step-0']/div[2]/button")).click().then(function () {
    console.log(chalk.red("有弹窗 ======"));
    // reExecution();
  }, function () {
    // callback();
    // console.log("没有弹窗-------");
  });
  callback();
}
// ====展开==============
async function showButton(){
  await driver.sleep(1 * 1000);
  await driver.findElement(By.xpath("//*[@id='non-empty-search-results']/div[2]/div/div[2]/div/div/div[1]/a/span")).click().then(() => {
    //获取文本
    getText();
  }, () => {
    //没有弹框  直接获取
    console.log(chalk.red("展开  --- 没有这个元素往下执行"));
    reExecution();
  });

}
async function getText(){
  let text = "";
  // ====获取 text()=============== 这个地方 黄色button 一般情况下会有一个，特殊情况会有两个   第二个咱不做兼容  ca   B0012AD748
  try{
    await driver.sleep(1 * 1000);
    await driver.findElement(By.id("a-autoid-2-announce")).getAttribute("textContent").then((res) => {
      text = Sw(res);
      console.log(text);
    });
    if (text === "Request approval") {
      let xPath = "";
      let bandText = "";
      let bandBoo = false;
      //// 不同的国家 UI 展示不一样
      if (!bandBoo) {
        xPath = "//*[@id='non-empty-search-results']/div[2]/div/div[2]/div/div/div[2]/div/div/div/div/div[1]/ul/li[1]/span/span";
        await driver.findElement(By.xpath(xPath)).getAttribute("textContent").then((res) => {
          bandText = Sw(res);
          console.log(chalk.blue(bandText));
          if (bandText.indexOf("brand") > -1) {
            bandBoo = true;
            console.log(chalk.green("保存asin--0000"));
          }
        }, () => {});
      }
      if (!bandBoo) {
        xPath = "//*[@id='non-empty-search-results']/div[2]/div/div[2]/div/div/div[2]/div/div/div/div/div[1]/ul/li[2]/span/span[2]";
        await driver.findElement(By.xpath(xPath)).getAttribute("textContent").then((res) => {
          bandText = Sw(res);
          console.log(chalk.blue(bandText));
          if (bandText.indexOf("brand") > -1) {
            bandBoo = true;
            console.log(chalk.green("保存asin--1111"));
          }
        }, () => {});
      }
      //这个xpath 很多都没有
      if (!bandBoo) {
        xPath = "//*[@id='non-empty-search-results']/div[2]/div/div[2]/div/div/div[2]/div/div/div/div/div[1]/ul/li[1]/span/span[2]";
        await driver.findElement(By.xpath(xPath)).getAttribute("textContent").then((res) => {
          bandText = Sw(res);
          console.log(chalk.blue(bandText));
          if (bandText.indexOf("brand") > -1) {
            bandBoo = true;
            console.log(chalk.green("保存asin--2222"));
          }
        }, () => {});
      }
      if (!bandBoo) {
        xPath = "//*[@id='non-empty-search-results']/div[2]/div/div[2]/div/div/div[2]/div/div/div/div/div[1]/ul/li[2]/span/span";
        await driver.findElement(By.xpath(xPath)).getAttribute("textContent").then((res) => {
          bandText = Sw(res);
          console.log(chalk.blue(bandText));
          if (bandText.indexOf("brand") > -1) {
            bandBoo = true;
            console.log(chalk.green("保存asin--3333"));
          }
        }, () => {});
      }
      if (!bandBoo) {
        xPath = "//*[@id='non-empty-search-results']/div[2]/div/div[2]/div/div/div[2]/div/div/div[1]/div/div[1]/ul/li/span/span";
        await driver.findElement(By.xpath(xPath)).getAttribute("textContent").then((res) => {
          bandText = Sw(res);
          console.log(chalk.blue(bandText));
          if (bandText.indexOf("brand") > -1) {
            bandBoo = true;
            console.log(chalk.green("保存asin--4444"));
          }
        }, () => {});
      }

      //如果有符合标准的保存
      if (bandBoo){
         saveAsin(asin);
         // 如果含有 brand 字段  则保存
      }

    }
    // / 跳过查看下一个  asin
    q += 1;
    if (q < asinArrLength) {
      searchAsin();
    } else {
      console.log(chalk.green("结束！"));
      driver.quit(); //关闭浏览器
    }
  }catch(err){
    console.log(err);
    console.log(chalk.red("网络不好弹窗没有出来，应该也没有asin"));
    reExecution();
  }

}

// 程序 开始 =============================
start();

// 跳过 执行下一个
function reExecution() {
  q += 1;
  searchAsin();
}

function Sw (str) {
  //去掉首尾两端的空格(^\s*)|(\s*$)
  return str.replace(/(^\s*)|(\s*$)/g, "");
}
